#!/bin/bash
#to summary the point error of follow-up telescopes at 08h every morning. 
Dir_now=$1
cd $Dir_now

xDefine ( )
{ 
aafit=`ls G*.new.fit | head -1`
CCDID=`gethead $aafit "telescop" | tr ',' ' ' | awk '{print($4"-"$2)}' ` 
timesobs=`gethead $aafit "date-obs"  | tr 'T' ' '  | awk '{print($1)}'`
echo $aafit $CCDID $timeobs
}

xCalDiff ( )
{
ls G*new.fit >listnew
rm -rf bb cc aa
for fitfile in `cat listnew`
do
	echo $fitfile
	gethead $fitfile "objctra" "objctdec" >aa
	ra=`cat aa | awk '{print($1)}'`
	dec=`cat aa | awk '{print($2)}'`
	xy2sky $fitfile 512 512 >bb
	rra=`cat bb | awk '{print($1)}'`
	rdec=`cat bb | awk '{print($2)}'`
	diffarcsec=`skycoor -r $ra $dec $rra $rdec | awk '{print($1/60)}'`
	objectname=`gethead $fitfile "object"`
	airmass=`gethead $fitfile "airmass"`
	jd=`gethead $fitfile "JD"`
	echo $jd $objectname $airmass $fitfile $diffarcsec | column -t >>cc
done
sort cc >tmp
mv tmp cc
firsttime=`head -1 cc | awk '{print($1)}'`
cat cc | awk '{print(($1-xxxx)*24*60,$2,$3,$4,$5)}' xxxx=$firsttime >tmp
mv tmp cc
}


xPlotDiff ( )
{
echo "xPlotDiff"
head -1 cc
pngfile=`echo $CCDID"-"$timesobs".png"`
titlename=`echo $CCDID"-"$timeobs"point_Error"`
echo $CCDID $timeobs
gnuplot <<EOF
set term png
set output "$pngfile"
set multiplot layout 2,1
set grid
set title "$titlename"
set xlabel "Since $firsttime (min)"
set ylabel "Point error (arcmin)"
plot 'cc' u 1:5 with p pt 1 ps 2
unset title
set xlabel "airmass"
set ylabel "Point error (arcmin)"
plot 'cc' u 3:5 with p pt 7 ps 2
EOF
#ls $pngfile
}

xChecktime ( )
{
        timeForWork=08 #local time
        StringTimeForWork=`date +%H`
 #       echo "$timeForWork , $StringTimeForWork"
        if [ ` echo " $StringTimeForWork == $timeForWork " | bc ` -eq 1  ]
        then
                echo "$StringTimeForWork == $timeForWork"
		xDefine
		xCalDiff
		xPlotDiff
                sleep 28800
        else
                #echo "$StringTimeForWork !== $timeForWork , go ahead"
                sleep 1

        fi

}
xChecktime

